<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\ContentResource;
use App\Models\Category;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{

    public function index()
    {
        $categories = Category::orderBy('path')->get();
        return CategoryResource::collection($categories);
    }


    public function store(Request $request, Category $category)
    {
        $request->validate([
            'title' => ['required'],
            'name' => ['required'],
        ], [
            'name.required' => '英文标识不能为空'
        ]);
        DB::beginTransaction();
        $category->fill($request->input());
        $category->user_id = Auth::id();
        $category->save();
        DB::commit();
        return $this->message('栏目添加成功');
    }


    public function show(Category $category)
    {
        return new CategoryResource($category);
    }


    public function edit(Category $category)
    {
        //
    }


    public function update(Request $request, Category $category)
    {
        $request->validate([
            'title' => ['required'],
            'name' => ['required'],
        ], [
            'name.required' => '英文标识不能为空'
        ]);
        DB::beginTransaction();
        $category->fill($request->input());
        $category->user_id = Auth::id();
        $category->save();
        DB::commit();
        return $this->message('栏目更新成功');
    }


    public function destroy(Category $category)
    {
        $category->delete();
        return $this->message('栏目删除成功');
    }

    /**
     * 按照栏目分类搜索
     * @param Request $request
     * @return Request|AnonymousResourceCollection
     */
    public function filter(Request $request, Category $category)
    {
        return ContentResource::collection($category->contents()->paginate(5));
    }
}
